package com.atguigu.guli.service.trade.controller.api;


import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.utils.JwtHelper;
import com.atguigu.guli.service.trade.entity.Order;
import com.atguigu.guli.service.trade.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2021-08-13
 */
@RestController
@RequestMapping("/api/trade/order")
public class ApiOrderController {
    //4、课程详情页 查询某个用户是否购买过该课程
    @GetMapping("auth/isBuy/{courseId}")
    public R isBuy(@PathVariable String courseId , HttpServletRequest request){
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getCourseId , courseId);
        queryWrapper.eq(Order::getMemberId , JwtHelper.getId(request));
        queryWrapper.eq(Order::getStatus , 1);//已支付
        Order order = orderService.getOne(queryWrapper);
        return  R.ok().data("isBuy" , order==null?"0" :"1");//1代表已购买该课程
    }

    //3、查询订单的支付状态
    @GetMapping("auth/getPayStatus/{orderId}")
    public R getPayStatus(@PathVariable String orderId){
        Order order = orderService.getById(orderId);
        return R.ok().data("status" ,order.getStatus()+"");
    }

    @Autowired
    OrderService orderService;
    //1.在课程详情页点击立即购买，创建订单，并返回订单id的接口
    @PostMapping("auth/createOrder/{courseId}")
    public R createOrder (HttpServletRequest request, @PathVariable String courseId){
        //创建订单需要：课程id和用户信息
        String memberId = JwtHelper.getId(request);
        String orderId = orderService.createOrder(memberId,courseId);
        return R.ok().data("id",orderId);
    }
    //2.根据订单id查询订单详情
    @GetMapping("auth/getOrder/{orderId}")
    public R getOrder(HttpServletRequest request,@PathVariable String orderId){
        String memberId = JwtHelper.getId(request);
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getId,orderId);
        queryWrapper.eq(Order::getMemberId,memberId);
        Order order = orderService.getOne(queryWrapper);

        return R.ok().data("item",order);
    }
}

